package com.common.weapp.service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.common.user.properties.WePropertites;
import com.common.util.crypto.WxMaCryptUtils;
import com.common.weapp.bean.WeJscode2SessionResult;
import com.common.weapp.bean.WeUser;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;


@Service
public class WeUserServiceImpl implements WeUserService {
		
	@Autowired
	private WePropertites wePropertites;
	
	 @Autowired  
	 private RestTemplate restTemplate; 
	 
	 @Autowired
	 private ObjectMapper objectMapper;

	@Override
	public WeJscode2SessionResult getSessionInfo(String jsCode) throws Exception {

		Map<String, String> params = new HashMap<>();
	    params.put("appid", wePropertites.getAppid());
	    params.put("secret", wePropertites.getSecret());
	    params.put("js_code", jsCode);
	    params.put("grant_type", "authorization_code");
	    
	    WeJscode2SessionResult result = restTemplate.getForObject(JSCODE_TO_SESSION_URL, WeJscode2SessionResult.class, params);
	    
	    return result;
	}

	@Override
	public WeUser getUserInfo(String sessionKey, String encryptedData, String ivStr) throws JsonParseException, JsonMappingException, IOException {
		String userInfo = WxMaCryptUtils.decrypt(sessionKey, encryptedData, ivStr);
		WeUser user = objectMapper.readValue(userInfo, WeUser.class);
		
		return user;
	}

	@Override
	public boolean checkUserInfo(String sessionKey, String rawData, String signature) {
		final String generatedSignature = DigestUtils.sha1Hex(rawData + sessionKey);
	    System.out.println(generatedSignature);
	    return generatedSignature.equals(signature);
	}

}
